package com.vayne.demo;

import com.vayne.api.DefaultPersonFactory;
import com.vayne.api.PersonFactory;
import com.vayne.bean.Person;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ServiceLoader;

/**
 * @author xuerui.zhang
 * @since 2020/4/6 下午9:53
 */
public class BeanInstanceDemo {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/bean_instance_config.xml");
        AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();

        Person bean = beanFactory.getBean("person-by-factory", Person.class);
        System.out.println(bean);

        ServiceLoader<PersonFactory> serviceLoader = beanFactory.getBean("serviceLoaderFactory", ServiceLoader.class);
        print(serviceLoader);

        PersonFactory personFactory = beanFactory.createBean(DefaultPersonFactory.class);
        System.out.println(personFactory.createPerson());
    }

    private static void print(ServiceLoader<PersonFactory> serviceLoader) {
        for (PersonFactory personFactory : serviceLoader) {
            System.out.println(personFactory.createPerson());
        }
    }
}
